package com.xjh.him.utils;

import android.annotation.TargetApi;
import android.app.Activity;
import android.graphics.Rect;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.EditText;

import com.xuexiang.xui.utils.DensityUtils;

public class KeyboardUtils {
    private static final String SHARED_SOFT_INPUT_HEIGHT = "shared_soft_input_height";
    private static final int DEFAULT_SOFT_INPUT_HEIGHT = DensityUtils.getDisplayMetrics().heightPixels / 3;

    public static boolean isSoftInputShow(Activity activity) {
        return com.xuexiang.xui.utils.KeyboardUtils.isSoftInputShow(activity);
    }

    public static void showSoftInput(EditText editText) {
        com.xuexiang.xui.utils.KeyboardUtils.showSoftInput(editText);
    }

    public static void hideSoftInput(View view) {
        com.xuexiang.xui.utils.KeyboardUtils.hideSoftInput(view);
    }

    public static void addKeyboardToggleListener(Activity activity, com.xuexiang.xui.utils.KeyboardUtils.SoftKeyboardToggleListener listener) {
        com.xuexiang.xui.utils.KeyboardUtils.addKeyboardToggleListener(activity, listener);
    }

    /**
     * 获取键盘高度
     * @return
     */
    public static int getKeyboardHeight() {
        return (int) MMKVUtils.get(SHARED_SOFT_INPUT_HEIGHT, DEFAULT_SOFT_INPUT_HEIGHT);
    }

    /**
     * 记录软键盘高度
     * @param activity
     * @return
     */
    public static boolean saveKeyboardHeight(Activity activity) {
        int screenHeight = activity.getWindow().getDecorView().getHeight(); // 不包括状态栏
        Rect rect = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        int displayHeight = rect.bottom - rect.top; // 应用高度，不包括状态栏
        int softInputHeight = screenHeight - displayHeight;
        // 减去底部虚拟按键栏高度
        if (Build.VERSION.SDK_INT >= 20) {
            softInputHeight = softInputHeight - getSoftButtonsBarHeight(activity);
        }
        if (softInputHeight > 0) {
            return MMKVUtils.put(SHARED_SOFT_INPUT_HEIGHT, softInputHeight);
        }
        return false;
    }

    /**
     * 底部虚拟按键栏的高度
     * @return
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    private static int getSoftButtonsBarHeight(Activity mActivity) {
        DisplayMetrics metrics = new DisplayMetrics();

        mActivity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int usableHeight = metrics.heightPixels;

        mActivity.getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
        int realHeight = metrics.heightPixels;
        if (realHeight > usableHeight) {
            return realHeight - usableHeight;
        } else {
            return 0;
        }
    }
}
